package com.myteam.fugaocrm.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;

import com.myteam.fugaocrm.modle.FgPosition;
import com.myteam.fugaocrm.service.PositionServiceImpl;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class PositionController {
	@Resource protected PositionServiceImpl positionServiceImpl;
	
	@RequestMapping("position/all")
	@ResponseBody
	public ModelAndView all(HttpServletRequest request, HttpServletResponse response) throws Exception {
		List<FgPosition> fgPositionList = positionServiceImpl.all();
		
		ModelAndView view = new ModelAndView();
		view.addObject("fgPositionList", fgPositionList);
		view.setViewName("arch_post.jsp");
		return view;
	}
	
	@RequestMapping("position/delete")
	@ResponseBody
	public ModelAndView delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Integer positionId = Integer.parseInt(request.getParameter("positionId").toString());
		
		positionServiceImpl.deleteOne(positionId);
		
		List<FgPosition> fgPositionList = positionServiceImpl.all();
		
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/position/all");
		return view;
	}
	
	@RequestMapping("position/insertorupdate")
	@ResponseBody
	public ModelAndView insertOrUpdate(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String positionIdStr = request.getParameter("positionId")+"";
		String positionName = request.getParameter("positionName")+"";
		
		//校验
		
		
		//插入或更新
		Date date = new Date();
		String staffName = request.getSession().getAttribute("staffName")+"";
		Map<String, Object> params = new HashMap<String, Object>();
		
		if("".equals(positionIdStr)) {
			//insert
			params.put("positionName", positionName);
			params.put("createdDate", date);
			params.put("createdUser", staffName);
			params.put("modifiedDate", date);
			params.put("modifiedUser", staffName);
			positionServiceImpl.insert(params);
		}else {
			//update
			Integer positionId = Integer.parseInt(positionIdStr);
			params.put("positionId", positionId);
			params.put("positionName", positionName);
			params.put("createdDate", date);
			params.put("createdUser", staffName);
			params.put("modifiedDate", date);
			params.put("modifiedUser", staffName);
			positionServiceImpl.update(params);
		}
		
		ModelAndView view = new ModelAndView();
		view.setViewName("redirect:/position/all");
		return view;
	}
}
